package com.hessentec.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by songzj on 2016/9/26.
 */
@Configuration("bbcDataSourceConfig")
@MapperScan(basePackages = "com.hessentec.mapper.bbc", sqlSessionFactoryRef = "bbcSqlSessionFactory")
public class BBCDataSource {


    @Bean(name = "bbcDataSource", destroyMethod = "close", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource.bbc", locations = "classpath:application.properties")
     public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Bean(name = "bbcTransactionDataSourceManager")
     public DataSourceTransactionManager transactionDataSourceManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "bbcSqlSessionFactory")
     public SqlSessionFactory sqlSessionFactory(@Qualifier("bbcDataSource") DataSource bbcDataSource) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(bbcDataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/hessentec/mapper/bbc/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }


}
